package com.miyake.server.dsaccess;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.miyake.client.datamanage.plugin.PluginProperty;
import com.miyake.server.DsPlugin;
import com.miyake.server.PMF;

public class PluginManager {
	private static PluginManager instance;
	
	private PluginManager() {
	}
	
	public static PluginManager getInstance() {
		if (instance == null) {
			instance = new PluginManager();
		}
		return instance;
	}

	private boolean exists(String url) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		boolean ret = false;
		try {
			String query = "select from " + DsPlugin.class.getName();
			List<DsPlugin> list = (List<DsPlugin>) pm.newQuery(query).execute();	
			for (DsPlugin n : list) {
				if (n.getUrl().equalsIgnoreCase(url)) {
					ret = true;
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			pm.close();
		}
		return ret;
	}
	
	public List<PluginProperty> getPluginList(int typeFile) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<PluginProperty> ret = new ArrayList<PluginProperty>();
		try {
			String query = "select from " + DsPlugin.class.getName();
			query += " where type == " + String.valueOf(typeFile);

			List<DsPlugin> list = (List<DsPlugin>) pm.newQuery(query).execute();	
			for (DsPlugin n : list) {
				ret.add(n.toRemoteObject());
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public String createPlugin(int typeAnalysis, String name, String url,
			String decription, String helpUrl, String provider, String version, String license) {
		if (exists(url)) {
			return null;
		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		DsPlugin plugin = new DsPlugin();
		plugin.setDescription(decription);
		plugin.setName(name);
		plugin.setType(typeAnalysis);
		plugin.setUrl(url);
		plugin.setHelpUrl(helpUrl);
		plugin.setProvider(provider);
		plugin.setVersion(version);
		plugin.setLicense(license);
		try {
			pm.makePersistent(plugin);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			pm.close();
		}
		return plugin.getEncodedKey();
	}

	public DsPlugin getPlugin(String key) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		DsPlugin plugin = null;
		try {
			plugin = pm.getObjectById(DsPlugin.class, key);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			pm.close();
		}
		return plugin;
	}

	public void delete(String key) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			DsPlugin plugin = pm.getObjectById(DsPlugin.class, key);
			pm.deletePersistent(plugin);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			pm.close();
		}
	}
}
